<template>
  <div>
    <van-tabbar v-model="active" v-if="showTabBar">
      <van-tabbar-item v-for="link in links" :key="link.url" :to="link.url" :icon="link.icon">
        {{ link.name }}
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup lang="ts">
import { ref, shallowRef, computed, watch } from 'vue';
import { useRoute } from 'vue-router';

const route = useRoute();

const active = ref(0);
const links = shallowRef([
  { id: 0, url: '/', name: '首页', icon: 'home-o' },
  { id: 1, url: '/category', name: '分类', icon: 'shop-o' },
  { id: 2, url: '/cart', name: '购物车', icon: 'cart-o' },
  { id: 3, url: '/my', name: '我的', icon: 'manager-o' }
]);

const calculateActiveIndex = () => {
  const index = links.value.findIndex(link => link.url === route.path);
  return index === -1 ? 0 : index;
};

watch(
  () => route.path,
  () => {
    active.value = calculateActiveIndex();
  },
  { immediate: true }
);

const showTabBar = computed(() => {
  return route.meta.showTabBar === true;
});
</script>

<style scoped lang="scss"></style>
